package com.base.study.activity;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.RequiresApi;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.base.commonlib.bean.VideoTimingEntity;
import com.base.commonlib.utils.DragImageUtils;
import com.base.commonlib.utils.RxBus2;
import com.base.commonlib.utils.ToastUtil;
import com.base.study.R;
import com.base.study.bean.CurriculumCatalogBean;
import com.base.study.bean.CurriculumIntroduceBean;
import com.base.study.databinding.ActivityCurriculumDetailBinding;
import com.base.study.fragment.CurriculumCatalogFragment;
import com.base.study.fragment.CurriculumIntroduceFragment;
import com.base.study.presenter.CurriculumDetailPresenter;
import com.base.study.view.CurriculumDetailView;
import com.base.video.CBaseVideoBarActivity;
import com.base.video.VideoStatEntity;
import com.base.video.ui.ControlPanel;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMWeb;

import java.io.Serializable;
import java.util.List;
import java.util.Random;

import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

/**
 * Created by zw on 2020/2/13.
 * 课程详情
 */

@Route(path = "/curriculum/detail")
public class CurriculumDetailActivity extends CBaseVideoBarActivity<CurriculumDetailPresenter> implements CurriculumDetailView,View.OnClickListener{

    private ActivityCurriculumDetailBinding mBinding;
    private CurriculumIntroduceFragment curriculumIntroduceFragment;
    private CurriculumCatalogFragment curriculumCatalogFragment;
    private FragmentManager mFragmentManager;
    private FragmentTransaction mTransaction;
    private Bundle bundle;
    private Disposable disposable;

    @Autowired
    public String id;

    @Autowired
    public String url;

    @Autowired
    public String courseRootId;

    private String pdfUrl = "";
    public boolean isShowTime;

    private int starTime = 0;
    public static final int START_STUDY = 3;//计时器
    public static final int IS_SHOW_TIME = 4;//验证是否显示
    public int studyTime = 0;
    public int endTime = new Random().nextInt(MINIESSS);
    public static final int MINIESSS = 600;

    @Override
    protected int getLayoutResource() {
        return R.layout.activity_curriculum_detail;
    }

    @Override
    protected void init() {
        super.init();
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
        mBinding = (ActivityCurriculumDetailBinding) mRootBinding;
        mPresenter=new CurriculumDetailPresenter(this,this);
        mPresenter.start();
        mPresenter.getInfo(id);
    }

    @Override
    protected void start() {
         bundle = new Bundle();
        bundle.putString("id",id);

        setBackNavigation();
        setBarTitle("课程详情");
        /*
        setRigImg(R.drawable.ic_title_share, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                UMImage thumb = new UMImage(mContext,"http://image.biaobaiju.com/uploads/20180803/23/1533308847-sJINRfclxg.jpeg");
                UMWeb web = new UMWeb("RealNetWorkUtil.HOST_IP+":8585/#/");
                web.setTitle("This is music title");//标题
                web.setThumb(thumb);  //缩略图
                web.setDescription("my description");//描述
                new ShareAction(CurriculumDetailActivity.this)
                        .withMedia(web)
                        .setDisplayList(SHARE_MEDIA.SINA,SHARE_MEDIA.QQ,SHARE_MEDIA.QZONE,SHARE_MEDIA.WEIXIN,SHARE_MEDIA.ALIPAY,SHARE_MEDIA.DINGTALK)
                        .setCallback(shareListener).open();
            }
        });

         */

        ControlPanel controlPanel = new ControlPanel(this);
//        controlPanel.setUpSeeEnablekProgress(false);
        VideoTimingEntity mEntity = new VideoTimingEntity();
        mEntity.setPercentage(50);
        controlPanel.setmVideoTimingEntity(mEntity);
        mBinding.videoview.setControlPanel(controlPanel);

        //required: set url
        mBinding.videoview.setThumbImg(url);
//        mBinding.videoview.start();

         disposable = RxBus2.getInstance().doSubscribe(CurriculumCatalogBean.WaresBean.class, new Consumer<CurriculumCatalogBean.WaresBean>() {

            @Override
            public void accept(CurriculumCatalogBean.WaresBean user) throws Exception {
                if (user.getUrl().endsWith("PDF")||user.getUrl().endsWith("pdf"))
                {
                    mBinding.llPdf.setVisibility(View.VISIBLE);
                    mBinding.videoview.setVisibility(View.GONE);
                    pdfUrl = user.getUrl();
                    mBinding.tvPdf.setText(user.getName());

                    ARouter.getInstance().build("/sweb/common")
                            .withInt("key",6)
                            .withString("name",mBinding.tvPdf.getText()+".pdf")
                            .withString("title","文件")
                            .withString("url",user.getUrl())
                            .navigation();
                }else {
                    mBinding.llPdf.setVisibility(View.GONE);
                    mBinding.videoview.setVisibility(View.VISIBLE);
                    mBinding.videoview.setUp(user.getUrl());
                    mBinding.videoview.start();

                }
            }
        });
        RxBus2.getInstance().addSubscription(this, disposable);

       mBinding.llPdf.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View view) {
               //pdf 预览
               if (TextUtils.isEmpty(pdfUrl)){
                   showMes("预览地址错误");
                   return;
               }
               ARouter.getInstance().build("/sweb/common")
                       .withInt("key",6)
                       .withString("name",mBinding.tvPdf.getText()+".pdf")
                       .withString("title","文件")
                       .withString("url",pdfUrl)
                       .navigation();
           }
       });


        disposable = RxBus2.getInstance().doSubscribe(VideoStatEntity.class, new Consumer<VideoStatEntity>() {
            @Override
            public void accept(VideoStatEntity bean) throws Exception {
                if (bean.getState() == 001) {
                   // mHandler.sendEmptyMessage(START_STUDY);
                    Log.e("xxx","getJifeng"+courseRootId);
                    mPresenter.getJifeng(courseRootId,mPresenter.mUser.getTenantId());
                   // mHandler.sendEmptyMessageDelayed(START_STUDY, 2000*60);
                }
            }
        });

    }

    //分享回调
    private UMShareListener shareListener = new UMShareListener() {
        /**
         * @descrption 分享开始的回调
         * @param platform 平台类型
         */
        @Override
        public void onStart(SHARE_MEDIA platform) {

        }

        /**
         * @descrption 分享成功的回调
         * @param platform 平台类型
         */
        @Override
        public void onResult(SHARE_MEDIA platform) {
            showMes("分享成功");
        }

        /**
         * @descrption 分享失败的回调
         * @param platform 平台类型
         * @param t 错误原因
         */
        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
           showMes("分享失败");
        }

        /**
         * @descrption 分享取消的回调
         * @param platform 平台类型
         */
        @Override
        public void onCancel(SHARE_MEDIA platform) {
            showMes("分享取消了");
        }
    };
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }

    private void initFragment() {
        mFragmentManager =getSupportFragmentManager();
        mTransaction = mFragmentManager.beginTransaction();
        curriculumIntroduceFragment = new CurriculumIntroduceFragment();
        mTransaction.add(R.id.curriculum_center_content, curriculumIntroduceFragment);
        mTransaction.commit();
        if (curriculumIntroduceFragment !=null){
            curriculumIntroduceFragment.setArguments(bundle);//数据传递到fragment中
        }
        mBinding.fgMyStudy.setEnabled(false);
        mBinding.fgOnlineStudy.setEnabled(true);
        mBinding.fgOnlineStudy.setOnClickListener(this);
        mBinding.fgMyStudy.setOnClickListener(this);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        UMShareAPI.get(this).release();
        mPresenter.release();
        if (disposable !=null){
            disposable.dispose();
        }
    }

    @Override
    public void onClick(View v) {
        int i = v.getId();
        if (i == R.id.fg_my_study) {
            if (mBinding.fgMyStudy.isEnabled()) {
                mBinding.fgOnlineStudy.setEnabled(true);
                mBinding.fgMyStudy.setEnabled(false);
            }
            mFragmentManager = getSupportFragmentManager();
            mTransaction = mFragmentManager.beginTransaction();
            if (curriculumIntroduceFragment == null) {
                curriculumIntroduceFragment = new CurriculumIntroduceFragment();
            }
            //curriculumIntroduceFragment.setArguments(bundle);//数据传递到fragment中
            mTransaction.hide(curriculumCatalogFragment);
            mTransaction.show(curriculumIntroduceFragment);
            mTransaction.commit();
        }
        else if (i == R.id.fg_online_study) {
            if (mBinding.fgOnlineStudy.isEnabled()) {
                mBinding.fgOnlineStudy.setEnabled(false);
                mBinding.fgMyStudy.setEnabled(true);
            }
            mFragmentManager =getSupportFragmentManager();
            mTransaction = mFragmentManager.beginTransaction();
            if (curriculumCatalogFragment == null) {
                curriculumCatalogFragment = new CurriculumCatalogFragment();
                mTransaction.add(R.id.curriculum_center_content, curriculumCatalogFragment);
            }
            curriculumCatalogFragment.setArguments(bundle);//数据传递到fragment中
            mTransaction.hide(curriculumIntroduceFragment);
            mTransaction.show(curriculumCatalogFragment);
            mTransaction.commit();

        }

    }

    private  CurriculumIntroduceBean mCurriculumIntroduceBean;

    @Override
    public void returnIntroduce(CurriculumIntroduceBean curriculumIntroduceBean) {
        mCurriculumIntroduceBean = curriculumIntroduceBean;
        mPresenter.getCatelogListData(id);

    }

    @Override
    public void returnIntroError() {
        ToastUtil.show("详情加载失败");
    }

    @Override
    public void returnCatalogList(List<CurriculumCatalogBean> curriculumCatalogBeans) {
        bundle.putSerializable("curriculumIntroduceBean",mCurriculumIntroduceBean);
        bundle.putSerializable("curriculumCatalogBeans", (Serializable) curriculumCatalogBeans);
        initFragment();
        curriculumIntroduceFragment.setArguments(bundle);//数据传递到fragment中
        if (curriculumCatalogBeans !=null && curriculumCatalogBeans.size()>0){
            if (curriculumCatalogBeans.get(0).getWares().size()>0){
                if (curriculumCatalogBeans.get(0).getWares().get(0).getUrl().endsWith("PDF")||curriculumCatalogBeans.get(0).getWares().get(0).getUrl().endsWith("pdf"))
                {
                    pdfUrl = curriculumCatalogBeans.get(0).getWares().get(0).getUrl();
                    mBinding.tvPdf.setText(curriculumCatalogBeans.get(0).getWares().get(0).getName());
                    mBinding.llPdf.setVisibility(View.VISIBLE);
                    mBinding.videoview.setVisibility(View.GONE);
                }else {
                    mBinding.llPdf.setVisibility(View.GONE);
                    mBinding.videoview.setVisibility(View.VISIBLE);
                    mBinding.videoview.setUp(curriculumCatalogBeans.get(0).getWares().get(0).getUrl());
                }
            }
        }

    }

    @Override
    public void returnCatalogError() {
        ToastUtil.show("目录加载失败");
    }




//    //计时器
//    public Handler mHandler = new Handler() {
//        @RequiresApi(api = Build.VERSION_CODES.M)
//        @Override
//        public void handleMessage(Message msg) {
//            switch (msg.what) {
//                case START_STUDY:
//                    studyTime++;
//                    Log.e("xxxxxxxxxxxx",starTime+ "秒");
//                    //ToastUtil.show(studyTime + "秒");
//                    mPresenter.getJifeng(courseRootId);
//                    mHandler.sendEmptyMessageDelayed(START_STUDY, 2000*60);
//                    break;
//                case IS_SHOW_TIME:
//                    isShowTime = false;
//                    break;
//            }
//        }
//    };

}
